import {
  Controller,
  Post,
  Body,
  Request,
  BadRequestException,
} from '@nestjs/common';
import { MailService } from './mail.service';
import { Public } from '../../../../../common/public.decorator';
import { SendEmailCodeBodyDto,SendEmailToAdminBodyDto } from './mail.create.dto';

@Controller('mail')
export class MailController {
  constructor(private readonly mailService: MailService) {}

  @Public()
  @Post('sendEmailCode')
  async sendEmailCode(@Body() body: SendEmailCodeBodyDto, @Request() req: any) {
    let ip = req.ip;
    if (ip.indexOf('::ffff:') !== -1) {
      ip = ip.substring(7);
    }
    try {
      const emailRes = await this.mailService.sendEmailCode(body, ip);
      if (emailRes.errno) {
        throw new BadRequestException({
          code: emailRes.errno,
          msg: '邮件发送错误',
          data: false,
        });
      }
      return {
        code: 200,
        msg: '发送成功',
        data: true,
      };
    } catch (e) {
      throw new BadRequestException({
        code: e.errno,
        msg: '邮件发送错误',
        data: false,
      });
    }
  }

  @Public()
  @Post('sendEmailToAdmin')
  async sendEmailToAdmin(@Body() body: SendEmailToAdminBodyDto) {
    const emailRes = await this.mailService.sendEmailToAdmin(body);
    if (emailRes.errno) {
      throw new BadRequestException('邮件发送错误');
    }
    return {
      data: '发送成功',
    };
  }
}
